package init

import (
	"driver_certification_srv/config"
	"driver_certification_srv/internal/dao"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
)

var err error

func init() {
	ZapInit()
	ConfigInit()
	NacosInit()
	MysqlInit()
	RedisInit()
}

func ZapInit() {
	con := zap.NewDevelopmentConfig()
	con.OutputPaths = []string{
		"./driver.log",
		"stdout",
	}
	build, _ := con.Build()
	zap.ReplaceGlobals(build)
}

func ConfigInit() {
	viper.SetConfigFile("./config.yaml")
	err = viper.ReadInConfig()
	if err != nil {
		zap.S().Error(err)
	}
	err = viper.Unmarshal(&config.AppConfig)
	if err != nil {
		zap.S().Error(err)
	}
}

func NacosInit() {
	C := config.AppConfig.Nacos
	os.MkdirAll("./tmp/nacos/log", 0777)
	os.MkdirAll("./tmp/nacos/cache", 0777)
	clientConfig := constant.ClientConfig{
		NamespaceId:         C.NameSpace, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "./tmp/nacos/log",
		CacheDir:            "./tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      C.Host,
			ContextPath: "/nacos",
			Port:        C.Port,
			Scheme:      "http",
		},
	}
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		zap.S().Error(err)
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: C.DataID,
		Group:  C.Group})
	if err != nil {
		zap.S().Error(err)
	}
	err = json.Unmarshal([]byte(content), &config.DataConfig)
	if err != nil {
		zap.S().Error(err)
	}
}

func MysqlInit() {
	C := config.DataConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True", C.User, C.Password, C.Host, C.Port, C.Database)
	config.DB, err = gorm.Open(mysql.Open(dsn))
	if err != nil {
		zap.S().Error(err)
	}
	err = config.DB.AutoMigrate(&dao.Driver{})
	if err != nil {
		zap.S().Error(err)
	}
}

func RedisInit() {
	C := config.DataConfig.Redis
	config.RDB = redis.NewClient(&redis.Options{
		Addr:     C.Host,
		Password: C.Password,
		DB:       C.DB,
	})
	err = config.RDB.Ping().Err()
	if err != nil {
		zap.S().Error(err)
	}
}
